package produce.headers;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * @author : xiaohong
 * @date : 2021/4/11 15:35
 */

@RestController
@RequestMapping("/headers")
public class HeadersController {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @GetMapping
    public String send(@RequestParam String msg, @RequestParam String key, @RequestParam String value){
        // headers 内容
        Map<String, Object> headers = new HashMap<>();
        headers.put(key, value);

        // 自定义消息属性
        MessageProperties messageProperties = new MessageProperties();
        // 为消息添加headers
        messageProperties.getHeaders().putAll(headers);

        // 创建消息
        Message message = new Message(msg.getBytes(), messageProperties);

        // 交换机名称  路由key/queue队列名称  消息内容
        // headers模式路由key必须为""
        rabbitTemplate.convertAndSend("headers_exchange",null,message);

        return "发送消息成功:  "+key+" : "+value;
    }

}
